import logging
import os
import time

from config.sys_path import LOG_DIR
from sample.common.read_config import conf


class AutoTestLog:
    def __init__(self, name='CASE_LOG', level='DEBUG', filename='log.log', sh_level='DEBUG', fh_level='DEBUG'):
        # 创建日志器
        self.logger = logging.getLogger(name)

        # 日志收集的级别,默认为最详细的DEBUG级
        self.logger.setLevel(level)

        # 创建日志存储路径
        if not os.path.exists(LOG_DIR):
            os.makedirs(LOG_DIR)
        log_path = os.path.join(LOG_DIR, filename)

        # 设置日志处理器（输出到文件）
        fh = logging.FileHandler(log_path, encoding='utf-8')

        # 设置日志处理器的输出级别
        fh.setLevel(fh_level)
        self.logger.addHandler(fh)

        # 设置日志输出格式
        formats = '%(asctime)s [%(filename)s-->line:%(lineno)d] %(levelname)s :%(message)s '
        log_fm = logging.Formatter(formats)
        fh.setFormatter(log_fm)

        # 日志输出到控制台
        # sh = logging.StreamHandler()
        # sh.setLevel(sh_level)
        # self.logger.addHandler(sh)
        # sh.setFormatter(log_fm)


# 获取日志器
my_log = AutoTestLog(
    name=conf.get('logging', 'name'),
    level=conf.get('logging', 'level'),
    filename=time.strftime('%Y%m%d_%H') + conf.get('logging', 'filename'),
    sh_level=conf.get('logging', 'sh_level'),
    fh_level=conf.get('logging', 'fh_level')
).logger
